package com.fjzn.detect.config.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


/**
 * Repeatable 过滤器
 * 
 * @author hellworld
 */
public class RepeatableFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    private static final String FLITER_TYPE = "multipart/form-data";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        try {

            if(request instanceof HttpServletRequest){
                HttpServletRequest req = (HttpServletRequest)request;
                String method = req.getMethod();
                String contentType = request.getContentType();
                if (method.compareTo("GET") == 0 || (contentType != null && contentType.contains(FLITER_TYPE))) {
                    filterChain.doFilter(request, response);
                } else {
                    HttpServletRequest requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request);
                    filterChain.doFilter(requestWrapper, response);
                }
                return;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy()
    {

    }
}
